package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioProperties minioProperties;

    @Autowired
    private MinioClient minioClient;

    @Override
    public String upload(MultipartFile file) {

//        创建桶
        makeBucket();

//        上传文件
//        获取到文件的初始名称  即xxx.xxx 进行处理
        String originalFilename = file.getOriginalFilename();
//        处理完之后获得后缀  为之后拼接做准备
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
//        获得UUID
        String uuid = UUID.randomUUID().toString();
        String result = uuid.replace("-", "");

//        获取时间路径
        String dateTime = new SimpleDateFormat("yyyy/MM").format(new Date());

//        http://192.168.126.128:9000/xxxx/xxxx/xxxx/xxx.xxx
//        拼接得到uri
        String uri = dateTime + "/" + result + substring;

        try {
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .object(uri)
                    .contentType(file.getContentType())
                    .stream(file.getInputStream(),file.getSize(),-1)
                    .build();

            minioClient.putObject(putObjectArgs);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return String.join("/", minioProperties.getEndpoint(),minioProperties.getBucketName(),uri);
    }

    private void makeBucket() {
        try {
//            不存在则创建  存在则不管
            BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder()
                    .bucket(minioProperties.getBucketName()).build();
            if (!minioClient.bucketExists(bucketExistsArgs)) {
                MakeBucketArgs makeBucketArgs = MakeBucketArgs.builder()
                        .bucket(minioProperties.getBucketName())
                        .build();
                minioClient.makeBucket(makeBucketArgs);

//          为bucket添加策略
                String config = """
                        {
                                      "Statement" : [ {
                                        "Action" : "s3:GetObject",
                                        "Effect" : "Allow",
                                        "Principal" : "*",
                                        "Resource" : "arn:aws:s3:::%s/*"
                                      } ],
                                      "Version" : "2012-10-17"
                                    }
                        """.formatted(minioProperties.getBucketName());

                SetBucketPolicyArgs bucketPolicyArgs = SetBucketPolicyArgs.builder()
                        .bucket(minioProperties.getBucketName())
                        .config(config).build();
                minioClient.setBucketPolicy(bucketPolicyArgs);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
